
var exitapp = false
angular.module('starter.controllers2', ['ionic', "checklist-model"])
.controller("InfoCtrl", function($scope, $stateParams, $state, $ionicPlatform, $ionicPopup, $window, $ionicLoading, $timeout,$cordovaSQLite, SOAP, LOGOUT){
    

    // $ionicPlatform.registerBackButtonAction(function (event) {
    //   console.log(JSON.stringify(event))
    //   console.log($state.current.name)
    //   if($state.current.name=="app.info" || $state.current.name == "login"){
    //   	if (exitapp == false){
    //   		exitapp = true
    //   		$ionicLoading.show({template: "再次按下返回退出"})
    //   		$timeout(function(){exitapp = false; $ionicLoading.hide()}, 2000)
    //   	} else {
    //   		navigator.app.exitApp()
    //   	}
    //   }
    //   else {
    //     navigator.app.backHistory();
    //   }
    // }, 100)

  $ionicLoading.show({template: '加载用户信息'}) 
  
  $scope.chapters = []



  SOAP.LoadCustomerInfo(function(res){
    $ionicLoading.hide()
    if(res.getLoadCustomerInfoResult().length > 0){
      $window.localStorage['cusInfo'] = res.getLoadCustomerInfoResult()
      $scope.userinfo = JSON.parse(res.getLoadCustomerInfoResult())[0]
    } else {
      $ionicPopup.alert({title: '获取个人信息失败'})
      window.location.href = '#/login'
    }
  },function(err){$ionicLoading.hide()}, $stateParams.cusId)

  $scope.logout = function(){
    $window.localStorage['cusInfo'] = "";
    $window.localStorage['cusId'] = "";
    cusId = null
    cusInfo = null
    console.log("log out redirect to login")
    $state.go("login")
  }

  $scope.checkupdate = function(){
    $ionicLoading.show({template: '检查中'})
    $timeout(function(){
      $ionicLoading.show({template: '已经是最新版本'})
      $timeout(function(){
        $ionicLoading.hide()
      },1200)
    }, 500)
  }
    $scope.downloadSubject = function(courseId, pay){
    SOAP.LoadNewCourseSubject_HadDistrict(
      function(res){
        var subIds = JSON.parse(res.getLoadNewCourseSubject_HadDistrictResult()).map(function(v){return v.isubjectid}).join(',')
        SOAP.LoadCourseSubjectListInfo(
          function(res2){
            JSON.parse(res2.getLoadCourseSubjectListInfoResult()).map(function(vv){
              if ($cordovaSQLite){
                $cordovaSQLite.execute(db, "insert into  coursesubject (bpicanswer, bpicquestion,brich, bstopflag, canswer, cdescription, " +
                  "cmaker, cquestion, csubjecttype, ctitle, dchangedate, ianswercount, ichapterid, ichaptertype," +
                  "icourseid, iindex, iscore, isubjectid, isubjecttype) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
                  [vv.bpicanswer, vv.bpicquestion, vv.brich, vv.bstopflag, vv.canswer, vv.cdescription, vv.cmaker, vv.cquestion, 
                   vv.csubjecttype, vv.ctitle, vv.dchangedate, vv.ianswercount, vv.ichapterid, vv.ichaptertype,
                   vv.icourseid, vv.iindex, vv.iscore, vv.isubjectid, vv.isubjecttype]).then(
                  function(res){console.log("insert done")},function(res){console.log("insert error")}
                  )
              }
            })
          },outputerrfun, courseId, subIds);
      },outputerrfun, courseId, pay, "", '2000-01-01');
  }
  $scope.redownload = function(){
    $ionicLoading.show({template: "重新下载题库..."})
    $timeout(function(){$ionicLoading.hide()}, 1000 * 60 * 5)
    var courseids = []
    $scope.downloadInfo = {totalChapterCount: 0, downloadChapterCount: 0}
    $cordovaSQLite.execute(db, "select distinct(icourseid) as icourseid from coursechapter where bdownload = 1", [])
    .then(function(res){
    	console.log("已下载课程")
      	console.log(JSON.stringify(res))
	    for (var i = 0; i < res.rows.length; ++i){
	 		courseids.push(res.rows.item(i).icourseid)
	    }
	    $.each(courseids, function(index,courseid){ //delete old courses
	    	$cordovaSQLite.execute(db, "delete from coursechapter where icourseid = ?", [courseid])
	      	.then(outputerrfun,outputerrfun)
	        $cordovaSQLite.execute(db, "delete from coursesubject where icourseid = ?", [courseid])
	        .then(outputerrfun, outputerrfun)
	    })
	   $.each(courseids, function(index, courseid){ //download new courses
	    	SOAP.LoadNewCourseChapter_HadDistrice( //章节数量
	            function(r){
	                $scope.newChapters = JSON.parse(r.getLoadNewCourseChapter_HadDistriceResult());
	                $scope.downloadInfo.totalChapterCount += $scope.newChapters.length
	                $scope.downloadSubject(courseid, 0);
	                $.each($scope.newChapters, function(index, value){
	                    SOAP.LoadCourseChapterInfo(
	                       function(res){
		                        var cs = JSON.parse(res.getLoadCourseChapterInfoResult())[0]
		                        $cordovaSQLite.execute(db, "select * from coursechapter where ichapterid = ?", [cs.ichapterid])
		                        .then(
		                          	function(res){
		                          	//console.log("select " + JSON.stringify(res))
			                          	if (res.rows.length == 0){
			                            	$cordovaSQLite.execute(db, "insert into coursechapter " + 
			                              		"(ballowtest, bendgrade, bstopflag, cchaptercode, cchaptername, cdcname, cmemo, dchangedate, " + 
			                              		"ichapterid,icount, icourseid, iexamtime, igrade, itype, bdownload ) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
			                              		[cs.ballowtest, cs.bendgrade, cs.bstopflag, cs.cchaptercode, cs.cchaptername, cs.cdcname, cs.cmemo, cs.dchangedate, cs.ichapterid, cs.icount, cs.icourseid, cs.iexamtime, cs.igrade, cs.itype,1]).then(
			                              		function(res){
			                                	//console.log("result" + JSON.stringify(res))},function(res){"error" + console.log(JSON.stringify(res))
			                              	})
			                          	} else {
			                            	$cordovaSQLite.execute(db, "update coursechapter set ballowtest = ?, bendgrade = ?, bstopflag = ?, cchaptercode = ?," +
			                              		"cchaptername = ?, cdcname = ?, cmemo = ?, dchangedate = ?, ichapterid = ?, icount = ?," +
			                              		"icourseid = ?, iexamtime = ?, igrade = ?, itype = ? , bdownload = ? where ichapterid = ?",
			                              		[cs.ballowtest, cs.bendgrade, cs.bstopflag, cs.cchaptercode, cs.cchaptername, cs.cdcname, cs.cmemo, cs.dchangedate, cs.ichapterid, cs.icount, cs.icourseid, cs.iexamtime, cs.igrade, cs.itype,cs.ichapterid],1).then(
			                              	function(res){
			                                	//console.log("result" + JSON.stringify(res))},function(res){"error" + console.log(JSON.stringify(res))
			                              	})
			                          	}
			                          	$scope.downloadInfo.downloadChapterCount++
			                          	var text = "章节内容下载中" + parseInt($scope.downloadInfo.downloadChapterCount/$scope.downloadInfo.totalChapterCount * 100) + '%'
			                          	$('#downloadPercent').text(text)
			                          	$('#downloadProgress').val($scope.downloadInfo.downloadChapterCount)
			                            if($scope.downloadInfo.downloadChapterCount == $scope.downloadInfo.totalChapterCount) {
			                            	console.log("downloading complete!!!")
			                            	$ionicLoading.hide()
			                          	}
		                        	},outputerrfun
		                        );
	                   	 	},
	                    	function(err){
	                      		console.log("error while downloading chapter")
	                    	}, value.ichapterid
	                    ); //load coursechapter from remote
	                })// for each chapter
	          	},
	          	function(err){console.log(JSON.stringify(err));$ionicLoading.hide()},
	          	courseid, 0, '', '2000-01-01'
	          	);
		})
    }, outputerrfun)
  }


})
